﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Indexes;
using EffiProz.Core.Errors;
using EffiProz.Core.Lib;


namespace EffiProz.Core
{
    public class SortAndSlice
    {
        public static SortAndSlice noSort = new SortAndSlice();
        public int[] sortOrder;
        public bool[] sortDescending;
        public bool[] sortNullsLast;
        public bool sortUnion;
        public EfzArrayList exprList = new EfzArrayList();
        public Expression limitCondition;
        public Index index;

        public SortAndSlice() { }

        public bool hasOrder()
        {
            return exprList.size() != 0;
        }

        public bool hasLimit()
        {
            return limitCondition != null;
        }

        public int getOrderLength()
        {
            return exprList.size();
        }

        public void addOrderExpression(Expression e)
        {
            exprList.add(e);
        }

        public void addLimitCondition(Expression expression)
        {
            limitCondition = expression;
        }

        public void prepare(QuerySpecification select)
        {

            int orderByColumnCount = exprList.size();

            if (orderByColumnCount == 0)
            {
                return;
            }

            sortOrder = new int[orderByColumnCount];
            sortDescending = new bool[orderByColumnCount];
            sortNullsLast = new bool[orderByColumnCount];

            for (int i = 0; i < orderByColumnCount; i++)
            {
                ExpressionOrderBy sort = (ExpressionOrderBy)exprList.get(i);

                if (sort.getLeftNode().queryTableColumnIndex == -1)
                {
                    sortOrder[i] = select.indexStartOrderBy + i;
                }
                else
                {
                    sortOrder[i] = sort.getLeftNode().queryTableColumnIndex;
                }

                sortDescending[i] = sort.isDescending();
                sortNullsLast[i] = sort.isNullsLast();
            }
        }

        public int getLimitStart(Session session)
        {

            if (limitCondition != null)
            {
                int? limit =
                    (int?)limitCondition.getLeftNode().getValue(session);

                if (limit != null)
                {
                    return (int)limit;
                }
            }

            return 0;
        }

        public int getLimitCount(Session session, int rowCount)
        {

            int limitCount = 0;

            if (limitCondition != null)
            {
                int? limit =
                    (int?)limitCondition.getRightNode().getValue(session);

                if (limit != null)
                {
                    limitCount = (int)limit;
                }
            }

            if (rowCount != 0 && (limitCount == 0 || rowCount < limitCount))
            {
                limitCount = rowCount;
            }

            return limitCount;
        }

        public void setIndex(TableBase table)
        {

            try
            {
                index = table.createAndAddIndexStructure(null, sortOrder,
                        sortDescending, sortNullsLast, false, false, false);
            }
            catch (Exception )
            {
                throw Error.runtimeError(ErrorCode.U_S0500, "SortAndSlice");
            }
        }
    }
}
